#include "../wmapp/wmapp.h"
#include "../wmapp/wmframe.h"
#include "../wmapp/wmwindow.h"
#include "../wmapp/wmtextbar.h"
#include "../wmapp/wmbutton.h"

#include <ctime>
#include <sstream>
#include <fstream>
#include <iostream>
#include <stdlib.h>
using namespace std;

#include "outside.xpm"
#include "people.xpm"
#include "sex.xpm"

string fname = string(getenv("HOME")) + string("/.wmhikikomori");
const char * filename = fname.c_str();
time_t ht, tt, st;

void writeline(ofstream &f, time_t x) {
	struct tm * t;
	char buffer[80];

	t = localtime(&x);
	strftime(buffer, 80, "%Y %m %d %H %M %S", t);
	f << buffer << endl;
}

void writelog() {
	ofstream f;
	f.open(filename, std::ios::out);
	writeline(f, ht);
	writeline(f, tt);
	writeline(f, st);
	f.close();
}

void checklog() {
	fstream f;
	f.open(filename, std::ios::in);
	if (f.is_open()) {
		f.close();
		return;
	} else
		writelog();
}

time_t readline(ifstream &f) {
	struct tm t;
	f >> t.tm_year >> t.tm_mon >> t.tm_mday >> t.tm_hour >> t.tm_min
			>> t.tm_sec;
	t.tm_year -= 1900;
	--t.tm_mon;
	return mktime(&t);
}

void readlog() {
	checklog();
	ifstream f;
	f.open(filename);
	ht = readline(f);
	tt = readline(f);
	st = readline(f);
	f.close();
}

string convert(int x) {
	stringstream ss;
	ss.fill('0');
	ss.width(6);
	ss << x;
	return ss.str();
}

void updatedays(const WMApp *a, WMWidget *w, void * p) {
	WMTextBar *b = dynamic_cast<WMTextBar *> (w);
	time_t * t = static_cast<time_t*> (p);
	double diff = difftime(time(0), *t);
	int days = diff / (60 * 60 * 24);
	b->settext(convert(days));
	a->repaint();
}

void reset(const WMApp *a, WMWidget *w, void * p) {
	time_t * t = (time_t*) p;
	*t = time(0);
	writelog();
	updatedays(a, w, p);
}
void makewindow(WMWindow *w) {
	ht = tt = st = time(0);
	readlog();

	static WMFrame top, mid, bottom, topleft, midleft, bottomleft;
	static WMTextBar h("000000", 0); //left house
	static WMTextBar t("000000", 0); // rl chat
	static WMTextBar s("000000", 0); // sex
	static WMButton hbtn, tbtn, sbtn;

	w->add_timed_function(500, updatedays, &h, &ht);
	w->add_timed_function(500, updatedays, &t, &tt);
	w->add_timed_function(500, updatedays, &s, &st);

	w->addchild(top);
	w->addchild(mid);
	w->addchild(bottom);
	w->setorientation(Orientation::Vertical);
	w->setaspectratios(1, 1, 1);

	top.addchild(hbtn);
	top.addchild(h);
	top.setaspectratios(1, 2);

	mid.addchild(tbtn);
	mid.addchild(t);
	mid.setaspectratios(1, 2);

	bottom.addchild(sbtn);
	bottom.addchild(s);
	bottom.setaspectratios(1, 2);

	hbtn.seticon(outside_xpm);
	tbtn.seticon(people_xpm);
	sbtn.seticon(sex_xpm);
	hbtn.addcallback(reset, &h, &ht);
	tbtn.addcallback(reset, &t, &tt);
	sbtn.addcallback(reset, &s, &st);

}
